# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

from django.shortcuts import render,redirect,render_to_response
from  django.http import  HttpResponse
from dwebsocket.decorators import accept_websocket, require_websocket

import paramiko

# Create your views here.

def index(request):
	return HttpResponse("okk")



def exec_command(comm):
    hostname = '10.1.126.22'
    username = 'yangqingxiang'
    password = 'yangqingxiang9811'

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, username=username, password=password)
    stdin, stdout, stderr = ssh.exec_command(comm)
    result = stdout.read()
    ssh.close()
    return result


@accept_websocket
def echo_once(request):
	if not request.is_websocket():
		try:  # 如果是普通的http方法
			message = request.GET['message']
			return HttpResponse(message)
		except:
			return render(request,'cmdb/websoket.html')
	else:
		for message in request.websocket:
			message = message.decode('utf-8')
			if message == 'backup_all':
				command = 'df -h'
				request.websocket.send(exec_command(command))
			else:
				request.websocket.send('小样儿，没权限!!!'.encode('utf-8'))


def connect_host(request,user_bind_host_id):
    # 如果当前请求不是websocket方式，则退出
    if not request.environ.get("wsgi.websocket"):
        return HttpResponse("错误，非websocket请求")
    try:
        remote_user_bind_host = request.user.account.host_user_binds.get(id=user_bind_host_id)
    except Exception as e:
        message = "无效的账户，或者无权访问"
    username = remote_user_bind_host.host.ip_addr
    print(username,request.META.get("REMOTE_ADDR"))
    message = "来自{remote}的请求 尝试连接 -> {username}@{hostname} <{ip}:{port}>".format(
        remote = request.META.get("REMOTE_ADDR"),# 请求地址
        username = remote_user_bind_host.host_user.username,
        hostname = remote_user_bind_host.host.hostname,
        ip = remote_user_bind_host.host.ip_addr,
        port = remote_user_bind_host.host.port,
    )
    bridge = WSSHBridge(request.environ.get("wsgi.websocket"),request.user)
    try:
        bridge.open(
            hostname=remote_user_bind_host.host.ip_addr,
            port=remote_user_bind_host.host.port,
            username=remote_user_bind_host.host_user.username,
            password=remote_user_bind_host.host_user.password,
                    )
    except Exception as e:
        message = "尝试连接{0}的过程中发生错误 ：{1}\n".format(remote_user_bind_host.host.hostname,e)
        return HttpResponse("错误！无法建立SSH连接！")

    print(request.GET.get("copytext"))
    bridge.shell()
    request.environ.get("wsgi.websocket").close()
    print("用户断开连接....")
    return HttpResponse("200,ok")